package com.lagou.controller;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Handler;

@RestController
public class GoController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    // 存放订单
    private ConcurrentHashMap<Long, Boolean> orderMap = new ConcurrentHashMap<>();

    /**
     * 下单
     *
     * @param id 订单id
     * @return
     */
    @RequestMapping("/order/{id}")
    public String order(@PathVariable Long id) {
        orderMap.put(id, false);
        rabbitTemplate.convertAndSend("ex.go", "go", id);
        return "任务已经下发，等待送单。。。";
    }

    /**
     * 支付
     *
     * @param id 订单id
     * @return
     */
    @RequestMapping("/pay/{id}")
    public String pay(@PathVariable Long id) {
        Long orderId = (Long) rabbitTemplate.receiveAndConvert("q.go");
        if (orderId != null && id.equals(orderId)) {
            orderMap.put(id, true);
            return "支付成功";
        } else {
            // 查询死信队列
            orderId = (Long) rabbitTemplate.receiveAndConvert("q.go.dlx");
            return "支付超时订单取消" + orderId;
        }
    }

    @RequestMapping("/notgo")
    public String getAccumulatedTask() {
        String notGo = (String) rabbitTemplate.receiveAndConvert("q.go.dlx");
        return notGo;
    }
}
